import Vue from 'vue'
import VueRouter from 'vue-router'
import Manager from '../views/Manager.vue'
import Login from '../views/Login.vue'

Vue.use(VueRouter)


//解决导航栏或者底部导航tabBar中的vue-router在3.0版本以上点击菜单报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: Manager,
    redirect: '/home', // 重定向
    children:[
      {path: 'home', name: 'Home', meta:{name: '系统首页'}, component: () => import("../views/manager/Home.vue")},
      {path: 'user', name: 'User', meta:{name: '用户信息'}, component: () => import("../views/manager/User.vue")},
      {path: '403', name: 'Unexpected', meta:{name: '无权限'}, component: () => import("../views/manager/Unexpected.vue")},
      {path: 'info', name: 'Info', meta:{name: '个人信息'}, component: () => import("../views/manager/Info.vue")},
      {path: 'pwd', name: 'Password', meta:{name: '修改密码'}, component: () => import("../views/manager/Password.vue")},
    ]
  },
  {
    path: '/login',
    name: '/login',
    meta:{name: '登录'},
    component: Login
  },
  {
    path: "/register",
    name: "register",
    meta:{name: '注册'},
    component: () => import("../views/Register.vue")
  },
  {
    path: '*',
    name: '404',
    meta:{name: '无法访问'},
    component: () => import("../views/manager/404.vue")
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next) =>{
// console.log(to,from,next)
//   to 是到达的路由信息
//   from 是开源的路由信息
//   next 是函数，调用next() 放行，调用next(path) 跳转
  let adminPaths = ['/user']
  let user = JSON.parse(localStorage.getItem('honey-user') || '{}')

  console.log(to)
  //如果当前登录的用户不是管理员,并且访问管理员权限的页面
  if(user.role !== 'ADMIN' && adminPaths.includes(to.path)){
    next('/403')
  }else{
    next()
  }
})

export default router